# This file is part of tryton-condominium module for Tryton. 
# The COPYRIGHT file at the top level of this repository contains 
# the full copyright notices and license terms.

import logging
from trytond.model import ModelView, ModelSQL, fields
from trytond.wizard import Wizard, StateView, Button, StateTransition
from trytond.pyson import Eval
from trytond.pool import Pool, PoolMeta
from trytond.transaction import Transaction

STATES = {
    'readonly': ~Eval('active', True),
    }
DEPENDS = ['active']

__all__ = ['Building', 
           'Floor', 
           'FloorIdent',
           'Party',
           'Apartment',
           'PartyApartment',
           'BuildingWizard',
           'BuildingCreateStart']

__metaclass__ = PoolMeta


class Building(ModelSQL, ModelView):
    __name__ = 'company.company'

    apartments = fields.One2Many('condominium.apartment', 'company', 'Apartments',
        states=STATES, depends=DEPENDS)
    uom = fields.Many2One('product.uom', 'Unit',
        states={'required': True,})

    @classmethod    
    def default_uom(cls):
        # Get m2 as default uom

        obj_data = Pool().get('ir.model.data')

        data = []
        data.append(('fs_id','=','uom_square_meter'))
        data.append(('module','=','product'))
        data.append(('model','=','product.uom'))

        data_id = obj_data.search(data)
        if not data_id:
            return None        
        res = obj_data.browse(data_id)
        return res[0].db_id


class Floor(ModelSQL, ModelView):
    'Building Floor'
    __name__  = 'condominium.floor'

    name = fields.Char('Name', required=True, translate=True)
    active = fields.Boolean('Active')

    @classmethod
    def __setup__(cls):
        super(Floor, cls).__setup__()
        cls._sql_constraints = [
            ('name_uniq', 'UNIQUE(name)', 'The floor name must be unique !'),
        ]

    @staticmethod
    def default_active():
        return True


class FloorIdent(ModelSQL, ModelView):
    'Building Floor Identifier. Ex A,B,C or North, South, etc.'
    __name__  = 'condominium.floor.ident'
    _description = __doc__

    name = fields.Char('Name', required=True, translate=True)
    active = fields.Boolean('Active')

    @classmethod
    def __setup__(cls):
        super(FloorIdent, cls).__setup__()
        cls._sql_constraints = [
            ('name_uniq', 'UNIQUE(name)', 'The floor identifier name must be unique !'),
        ]

    @staticmethod
    def default_active():
        return True


class Party(ModelSQL):
    'Party to apartments'
    __name__  = 'party.party'

    apartments = fields.One2Many('condominium.apartment', 'party', 'Apartments',
        states=STATES, depends=DEPENDS)


class PartyApartment(ModelSQL):
    'Owner - Apartment'
    __name__  = 'party.party-condominium.apartment'
    _table = 'condominium_owner_apartment_rel'

    owner = fields.Many2One('party.party', 'Owner', ondelete='CASCADE',
            required=True, select=True)
    apartment = fields.Many2One('condominium.apartment', 'Apartment',
        ondelete='CASCADE', required=True, select=True)


class Apartment(ModelSQL, ModelView):
    'Apartment'
    __name__  = 'condominium.apartment'

    party = fields.Many2One('party.party', 'Party',
            required=True, ondelete='CASCADE', select=True)
    company = fields.Many2One('company.company', 'Building',
            required=True, select=True)
    floor = fields.Many2One('condominium.floor', 'Floor',
            required=True)
    floor_ident = fields.Many2One('condominium.floor.ident', 'Floor identifier')
    owners = fields.Many2Many('party.party-condominium.apartment',
        'owner', 'apartment', 'Owners', states=STATES, depends=DEPENDS)

    # Observaciones
    # area --> m2 - Ver Building.uom
    # factor --> La suma de los factores de todos los apartamentos 
    #            de un edificio debe ser igual a 1
    # status --> Arrendado, por Arrendar, Para Venta, Empty

    @classmethod
    def delete(cls, ids):
        party_obj = Pool().get('party.party')

        if isinstance(ids, (int, long)):
            ids = [ids]

        # Get the parties before we delete the apartments.
        apartments = self.browse(ids)
        party_ids = [apartment.party.id for apartment in apartments]

        res = super(Apartment, cls).delete(ids)

        # Get parties that are still linked after delete.
        parties = party_obj.browse(party_ids)
        unlinked_party_ids = [party.id for party in parties \
                                 if not party.apartments]
        if unlinked_party_ids:
            party_obj.delete(unlinked_party_ids)

        return res

# Wizard for Building creation. 

class BuildingWizard(Wizard):
    "Creates a Building"
    __name__ = "condominium.building.create"  # El nombre del Wizard

    start = StateView('company.company',
        'company.company_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Next', 'company', 'tryton-ok', True), # Go to company StateView (next step)
            ])

    company = StateView('condominium.building.create.start',
        'condominium.building_creation_start_view_form', [
            Button('Cancel', 'end', 'tryton-cancel', default=True),
            Button('Create', 'create_', 'tryton-ok'),  # Go to create_
            ])

    create_ = StateTransition()


    def transition_create_(self):
        logger = logging.getLogger('building')

        logger.info("Creating a new building '" + self.start.party.name + "'")
        self.start.save()
        logger.info('Building created with id: ' + str(self.start.id))
        return 'end'



class BuildingCreateStart(ModelView):
    "Creates a Building"
    __name__ = 'condominium.building.create.start'

    # Aqui van los campos con la informacion que queremos para crear la empresa

    admin_user = fields.Char('Usuario administrador', required=True)
    prefix = fields.Char('Sequence Prefix', size=2)
    alias = fields.Char('Alias. Ej. MAREA MULTIPLAZA', size=20)
    contabilidad = fields.Boolean('Crear contabilidad')
    tax_venta = fields.Boolean('Impuesto a las ventas')















